<template>
  <el-card class="search-bar">
    <el-row>
      <el-col :span="22">
        <el-icon>
          <Search />
        </el-icon>
        <span>搜索</span>
      </el-col>
      <el-col :span="2">
        <el-button>重置</el-button>
        <el-button type="primary" @click="getData">搜索</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="2" class="tar">
        <span>账号/姓名：</span>
      </el-col>
      <el-col :span="22">
        <el-input v-model="params.keyword"></el-input>
      </el-col>
    </el-row>
  </el-card>
  <el-card>
    <el-row>
      <el-col :span="23"></el-col>
      <el-col :span="1">
        <el-button type="primary" @click="addfn">添加</el-button>
      </el-col>
    </el-row>
  </el-card>
  <el-table :data="list" :border="true" :stripe="true">
    <el-table-column prop="id" label="编号" />
    <el-table-column prop="username" label="账号" />
    <el-table-column prop="nickName" label="姓名" />
    <el-table-column prop="email" label="邮箱" />
    <el-table-column prop="createTime" label="添加时间">
      <template #default="scope">
        {{ formatDate(scope.row.createTime) }}
      </template>
    </el-table-column>
    <el-table-column prop="loginTime" label="最后登录">
      <template #default="scope">
        {{ formatDate(scope.row.loginTime) }}
      </template>
    </el-table-column>
    <el-table-column prop="status" label="是否启用">
      <template #default="{ row }">
        <el-switch v-model="row.status" :active-value="1" :inactive-value="0" @change="changeStatus(row)" />
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="{ row }">
        <el-button link type="primary" v-permission="'allocRole'" @click="AllocRoleFn(row.id)">分配角色</el-button>
        <el-button link type="primary" v-permission="'editUser'" @click="editfn(row.id)">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="page">
    <ElConfigProvider :locale="zhCn">
      <el-pagination v-model:current-page="params.pageNum" v-model:page-size="params.pageSize"
        :page-sizes="[10, 20, 50, 100]" :small="true" :background="true" layout="total, sizes, prev, pager, next, jumper"
        :total="count" />
    </ElConfigProvider>
  </div>
  <EditUserVue v-model="addUserDialogShow" v-model:editId="editId" title="添加用户" />
  <AllocRoleVue v-model="allocRoleDialogShow" v-model:allocId="allocRoleId" />
</template>
<script setup lang='ts'>
import { userListDataApi, disabledUserApi } from '@/api'
import { reactive, ref, watch } from 'vue';
import { formatDate } from '@/utils/date'
import { Search } from '@element-plus/icons-vue'
import { ElConfigProvider, ElMessage } from 'element-plus'
import EditUserVue from './editUser.vue';
import axios from 'axios'
import AllocRoleVue from './allocRole.vue'
// @ts-ignore -- 这个注释的作用，让ts检查到这一行，别管
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
const list = ref<IUserModel[]>([])
// 数据总条数
const count = ref(0)
// 请求参数是和页面上的 表单相关联的所以需要在外面声明进行后续绑定
const params = reactive<IUserListParams>({
  keyword: '',
  pageNum: 1,
  pageSize: 10
})

// 定义取消请求相关的变量
let getting = false; // 是否正在请求中
let source: any;
function getData() {
  getting = true;
  source = axios.CancelToken.source();
  userListDataApi(params, source.token).then(res => {
    if (res.code === 200) {
      list.value = res.data.list;
      count.value = res.data.total;
    }
  }).finally(() => {
    getting = false
  })
}
getData();

// 当 pageNum 和 pageSize 发生变化时，重新请求数据
watch([() => params.pageNum, () => params.pageSize], (newVals, oldVals) => {
  // 如果变化的是 pageSize , 需要把pageNum 重置为1，保证一定有数据出现
  let [, newPage] = newVals;
  let [, oldPage] = oldVals;
  if (newPage !== oldPage) {
    params.pageNum = 1
  }
  // 我们发现，如果当pageNum比较大，切换了pageSize，可能会导致数据不够了，我们我解决方案是当pageSize变化时，pageNum重置为1。但是这样做导致两个数据都变了，发送了两次请求
  // 解决方案： 当发送第二次请求的时候，判断第一次是否还在请求中，如果还在请求中，则取消上一次请求
  // 如何取消

  // 如果正在请求中
  if (getting) {
    // 取消上一次请求
    source.cancel();
  }
  getData()
})


// 添加新用户
const addUserDialogShow = ref(false);
const addfn = () => {
  // 弹出一个用于添加的表单
  addUserDialogShow.value = true;
}

const editId = ref(0)
const editfn = (id: number) => {
  // 弹出dialog
  addUserDialogShow.value = true;
  editId.value = id
}

const changeStatus = (row: IUserModel) => {
  // console.log(row.status);
  disabledUserApi(row.id, row.status).then(res => {
    if (res.code === 200) {
      ElMessage.success('修改成功')
    } else {
      // 强调： 写业务，一定不是仅仅是成功的，一定还要考虑失败的情况
      // 状态回退
      row.status = row.status === 1 ? 0 : 1
    }
  }).catch(err => {
    // 状态回退
    row.status = row.status === 1 ? 0 : 1
  })
}


// 分配角色的逻辑
const allocRoleDialogShow = ref(false);
const allocRoleId = ref(0);
const AllocRoleFn = (id: number) => {
  allocRoleDialogShow.value = true;
  allocRoleId.value = id;
}

</script>
<style lang="less" scoped>
.el-card {
  margin-bottom: 20px;
}

.search-bar {
  .el-row {
    margin-top: 20px;
  }

  .el-input {
    width: 240px;
  }
}

.page {
  padding: 20px 0;
  display: flex;
  flex-direction: row-reverse;
}
</style>